package com.example.onlinetaxi.ui.activity.HomePage;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.callback.HomeCallBack.IExchangeLoginMode;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.ui.activity.Driver.MainPage.DriverMainActivity;
import com.example.onlinetaxi.ui.activity.MainPage.MainActivity;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.SharedPreferenceUtil.Storage;
import com.example.onlinetaxi.util.phoneUtil.PhoneUtil;
import com.example.onlinetaxi.view.VerifyCodeButton;

import java.util.HashMap;
import java.util.Map;

// 使用短信验证码登陆的fragment
public class VerifyCodeLoginFragment extends Fragment {

    private View rootView;
    private TextView exchangeTV;

    // 输入框
    private EditText phoneEt;
    private EditText verifyCodeEt;
    private VerifyCodeButton verifyCodeButton;
    private Button loginBtn;

    // 用户输入
    private String phoneStr;
    private String verifyCodeStr;

    // 响应体
    private DataResponse dataResponse;

    private IExchangeLoginMode exchangeLoginMode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 确保只赋值一次
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_verify_code_login, container, false);
        }

        // 初始化控件
        initView();

        // 获取交换控件
        exchangeTV = rootView.findViewById(R.id.login_tv_exchange);
        // 为控件添加事件
        initEvent();

        return rootView;
    }

    private void initView() {
        phoneEt = rootView.findViewById(R.id.verify_login_et_phone);
        verifyCodeEt = rootView.findViewById(R.id.login_et_verifyCode);
        verifyCodeButton = rootView.findViewById(R.id.get_login_verification_code);
        loginBtn = rootView.findViewById(R.id.verify_login_btn);
    }

    // 用来接收父类实现的接口（callBack）
    public void setExchangeLoginMode(IExchangeLoginMode exchangeLoginMode) {
        this.exchangeLoginMode = exchangeLoginMode;
    }

    private void initEvent() {
        exchangeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 进行登录模式的切换
                exchangeLoginMode.exchangeLoginMode();
            }
        });
        // 登录按钮
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 对用户输入进行验证
                if (isCorrect()) {
                    // 通过验证
                    // 向后端发起注册请求
                    if (sendLoginRequest()) {
                        // 提示用户注册成功
                        Toast.makeText(getActivity(), "登录成功！", Toast.LENGTH_SHORT).show();

                        // 手机号
                        LocalStorage.phone = phoneStr;
                        // 用户类型
                        LocalStorage.type = dataResponse.getData().get("type").toString();

                        // 用户退出登录时必须清除这些信息
                        // 将用户登录使用的手机号保存在sharedPreference中
                        Storage.putString(getActivity(), "phone", phoneStr);

                        // 根据用户类型进行页面跳转
                        if (LocalStorage.type.equals("passenger")){
                            Intent intent = new Intent(getActivity(), MainActivity.class);
                            startActivity(intent);
                        }else if (LocalStorage.type.equals("driver")){
                            Intent intent = new Intent(getActivity(), DriverMainActivity.class);
                            startActivity(intent);
                        }
                        // 结束登录界面
                        getActivity().finish();
                    }
                } else {
                    // 提示用户输入不合理
                    Toast.makeText(getActivity(), "手机号输入错误！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // 获取验证码按钮
        verifyCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取手机号
                phoneStr = phoneEt.getText().toString();

                // 判断phone的值是否合适
                boolean isPhone = PhoneUtil.isMobileNO(phoneStr);
                if (!isPhone) {
                    // 手机号错误
                    Toast.makeText(getActivity(), "手机号格式错误！", Toast.LENGTH_SHORT).show();
                } else {
                    // 提示用户发送成功
                    Toast.makeText(getActivity(), "短信验证码已发送！", Toast.LENGTH_SHORT).show();
                    // 设置验证码输入框获取焦点
                    verifyCodeEt.setFocusable(true);
                    verifyCodeEt.requestFocus();

                    // 按钮不可再点击
                    verifyCodeButton.start();

                    // 核心：设置向后台提交的参数
                    Map<String, String> map = new HashMap<>();
                    map.put("phone", phoneStr);
                    // 发送post异步请求
                    String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "SMS", "loginMessage");
                    // 接收响应体
                    DataResponse dataResponse = GetDataResponse.getDataResponse(response);
                    if (dataResponse.getCode().equals("200")) {
                        // 请求发送成功
                        Log.e("validate-code", dataResponse.getData().get("validate-code").toString());
                    } else {
                        Toast.makeText(getActivity(), dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private boolean isCorrect() {
        // 获取用户输入
        phoneStr = phoneEt.getText().toString();
        verifyCodeStr = verifyCodeEt.getText().toString();

        // 验证用户输入合理性
        if (phoneStr == null || phoneStr.equals("")) {
            return false;
        }
        // 判断电话号格式是否正确
        if (!PhoneUtil.isMobileNO(phoneStr)) {
            return false;
        }

        return true;
    }

    private boolean sendLoginRequest() {
        // 向后端发起请求
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneStr);
        map.put("verifyCode", verifyCodeStr);

        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "login", "verifyCodeLogin");
        dataResponse = GetDataResponse.getDataResponse(response);

        if (dataResponse.getCode().equals("200")) {
            // 用户登录成功
            return true;
        } else {
            // 提示错误信息
            Toast.makeText(getActivity(), dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}